# Copyright (c) 2018 Presto Labs Pte. Ltd.
# Author: leon

import logging

import tabulate

from coin.exchange.okex_futures.ws.limit_price_checker.per_product import (
    PerProductLimitPriceChecker, PerProductLimitPriceCheckerStatus)


class LimitPriceChecker(object):
  def __init__(self, *, logger=None):
    self._products = set()
    self._per_product = {}
    self._logger = logger or logging.getLogger(__name__)

  def add_product(self, product):
    self._products.add(product)
    self._per_product = {
        product: PerProductLimitPriceChecker(product=product, logger=self._logger)
        for product in self._products
    }

  def on_book(self, *, product, book, timestamp):
    per_product = self._per_product.get(product, None)
    if per_product:
      per_product.on_book(book=book, timestamp=timestamp)

  def on_ticker(self, *, product, ticker_event, timestamp):
    per_product = self._per_product.get(product, None)
    if per_product:
      per_product.on_ticker(ticker_event=ticker_event, timestamp=timestamp)

  def check_state(self, *, timestamp=None):
    for per_product in self._per_product.values():
      if not per_product.valid:
        return False
    return True

  def print_status(self, timestamp=None):
    headers = PerProductLimitPriceCheckerStatus._fields
    table = [
        per_product.get_status(timestamp=timestamp) for per_product in self._per_product.values()
    ]
    output = tabulate.tabulate(table, headers=headers)
    self._logger.info('\n' + output)
